package com.ruoyi.fjtseac.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件校验类
 *
 * @author zzl
 * @date 2022/7/18 21:07
 */
public class FileVerification {
    @Value("${path.video}")
    private String video;
    @Value("${path.audio}")
    private String audio;
    @Value("${path.image}")
    private String image;

    public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};

    public static final String[] AUDIO_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi",
            "asf", "rm", "rmvb"};

    public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"};


    /**
     * 判断文件名后缀是否为合法后缀
     *
     * @param file             上传的文件
     * @param allowedExtension 允许的文件类型后缀
     * @return
     */
    private boolean isAllowedExtension(MultipartFile file, String[] allowedExtension) {

        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否为图片
     *
     * @param file 图片文件
     * @return
     */
    private boolean isImage(MultipartFile file) {

        if (isAllowedExtension(file, IMAGE_EXTENSION)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为音频
     *
     * @param file 音频文件
     * @return
     */
    private boolean isAudio(MultipartFile file) {

        if (isAllowedExtension(file, AUDIO_EXTENSION)) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为视频
     *
     * @param file 视频文件
     * @return
     */
    private boolean isVideo(MultipartFile file) {
        if (isAllowedExtension(file, VIDEO_EXTENSION)) {
            return true;
        }
        return false;
    }

    /**
     * 判断文件名是否为对应文件夹的类型，文件后缀拦截 (提供文件校验的总接口)
     * @param file 用户上传的文件
     * @param type 文件夹所要求的类型，用以控制存放的二级文件夹。
     * @return
     */
    public boolean extensionFilter(MultipartFile file, String type) {
        if (Constants.VIDEO.equals(type)){
            return isVideo(file);
        }else if (Constants.AUDIO.equals(type)) {
            return isAudio(file);
        }else if (Constants.IMAGE.equals(type)) {
            return isImage(file);
        }else {
            return false;
        }
    }

}
